document.addEventListener('DOMContentLoaded', () => {
  const logsContainer = document.getElementById('logs-container') as HTMLElement;
  const clearLogsBtn = document.getElementById('clear-logs-btn') as HTMLButtonElement;
  const exportLogsBtn = document.getElementById('export-logs-btn') as HTMLButtonElement;

  const renderLogs = (errors: any[]) => {
    logsContainer.innerHTML = '';
    if (!errors || errors.length === 0) {
      logsContainer.textContent = 'No errors logged yet.';
      return;
    }

    errors.forEach(log => {
      const logEntry = document.createElement('div');
      logEntry.className = 'log-entry';

      const meta = document.createElement('div');
      meta.className = 'log-meta';
      meta.textContent = `[${new Date(log.timestamp).toLocaleString()}] Context: ${log.context}`;

      const message = document.createElement('div');
      message.className = 'log-message';
      message.textContent = log.error;

      logEntry.appendChild(meta);
      logEntry.appendChild(message);
      logsContainer.appendChild(logEntry);
    });
  };

  const loadLogs = () => {
    chrome.storage.local.get('errors', ({ errors }) => {
      renderLogs(errors);
    });
  };

  clearLogsBtn.addEventListener('click', () => {
    chrome.storage.local.set({ errors: [] }, () => {
      loadLogs();
    });
  });

  exportLogsBtn.addEventListener('click', () => {
    chrome.storage.local.get('errors', ({ errors }) => {
      if (errors) {
        const blob = new Blob([JSON.stringify(errors, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `autoplayer-logs-${Date.now()}.json`;
        a.click();
        URL.revokeObjectURL(url);
      }
    });
  });

  loadLogs();
});